package com.nmdl.print.utils;

import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hprt.lib.mt800.HPRTPrinterHelper;
import com.hprt.lib.mt800.exception.CustomerCodeException;
import com.nmdl.print.R;

public class DeviceConnectFragment extends DialogFragment {
    private boolean mIsShowAnimation = true;
    private IntentFilter intentFilter;
    private BluetoothReceiver bluetoothReceiver;
    private BluetoothAdapter bluetoothAdapter;
    private DevicesAdapter devicesAdapter;
    private OnConnectBack onConnectBack;
    private LinearLayout progress_bar_layout;
    private static final String TAG = "DeviceConnectFragment";

    public static DeviceConnectFragment newInstance(OnConnectBack onConnectBack) {
        DeviceConnectFragment fragment = new DeviceConnectFragment(onConnectBack);
        return fragment;
    }

    public DeviceConnectFragment(OnConnectBack onConnectBack) {
        this.onConnectBack = onConnectBack;
    }

    @Override
    public void onStart() {
        super.onStart();
        initDialog();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View mRootView = inflater.inflate(getLayoutId(), container, false);
        initView(mRootView);
        initEventAndData();
        return mRootView;
    }

    private int getLayoutId() {
        return R.layout.fragment_blue_tooth;
    }

    private void initView(View mRootView) {
        progress_bar_layout = mRootView.findViewById(R.id.progress_bar_layout);
        RecyclerView device_rv = mRootView.findViewById(R.id.device_rv);
        devicesAdapter = new DevicesAdapter(getActivity(), bluetoothDevice -> {
            //连接设备
            if (bluetoothDevice != null && onConnectBack != null) {
                bluetoothAdapter.cancelDiscovery();
                progress_bar_layout.setVisibility(View.INVISIBLE);
                showShort("连接打印机中...");
                dismiss();
                onConnectBack.back(bluetoothDevice);
            }
        });
        device_rv.setAdapter(devicesAdapter);
        device_rv.setLayoutManager(new LinearLayoutManager(this.getActivity()));
    }

    private void initEventAndData() {
        initReceiver();
        initBlueTooth();
    }

    private void initBlueTooth() {
        intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        //
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        //
        getActivity().registerReceiver(bluetoothReceiver, intentFilter);
        bluetoothAdapter.enable();
        bluetoothAdapter.startDiscovery();
        progress_bar_layout.setVisibility(View.VISIBLE);
    }

    private void initReceiver() {
        bluetoothReceiver = new BluetoothReceiver(new BluetoothReceiver.BluetoothListener() {
            @Override
            public void onDiscoveryStart() {
                Log.i(TAG, "onDiscoveryStart");
            }

            @Override
            public void onDeviceFound(BluetoothDevice device) {
                for (BluetoothDevice bluetoothDevice : devicesAdapter.getData()) {
                    if (bluetoothDevice.getName().equals(device.getName())) {
                        return;
                    }
                }
                devicesAdapter.addData(device);
                Log.i(TAG, "onDeviceFound -> ${device.name}");
            }

            @Override
            public void onDeviceBondStateChange(Integer state) {
                switch (state) {
                    case BluetoothDevice.BOND_NONE:
                        Log.i(TAG, "配对失败");
                        break;
                    case BluetoothDevice.BOND_BONDING:
                        Log.i(TAG, "正在配对");
                        break;
                    case BluetoothDevice.BOND_BONDED:
                        Log.i(TAG, "配对成功");
                        break;
                    default:
                        Log.i(TAG, "onDeviceBondStateChange -> UnKnow");
                        break;
                }
            }

            @Override
            public void onDeviceLost(BluetoothDevice device) {
                Log.i(TAG, "onDeviceLost 设备丢失 -> $device");
            }

            @Override
            public void onBluetoothStateChange(Integer state) {
                Log.i(TAG, "onBluetoothStateChange -> $state");
                switch (state) {
                    case BluetoothAdapter.STATE_OFF:
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF:
                        break;
                    case BluetoothAdapter.STATE_ON:
                        break;
                    case BluetoothAdapter.STATE_TURNING_ON:
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onDiscoveryFinish() {
                Log.i(TAG, "onDiscoveryFinish");
                progress_bar_layout.setVisibility(View.INVISIBLE);
                if (devicesAdapter.getData().size() <= 0) showShort("没有找到打印机设备！");
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy-------");
        bluetoothAdapter.cancelDiscovery();
        getActivity().unregisterReceiver(bluetoothReceiver);
    }

    private void initDialog() {
        //设置dialog样式
        Dialog dialog = getDialog();
        //dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //设置window样式
        Window window = dialog.getWindow();
        if (window != null) {
            if (mIsShowAnimation)
                window.getAttributes().windowAnimations = R.style.DatePickerDialogAnim;
            WindowManager.LayoutParams lp = window.getAttributes();
            lp.gravity = Gravity.BOTTOM; // 紧贴底部
            lp.width = WindowManager.LayoutParams.MATCH_PARENT; // 宽度持平
            lp.dimAmount = 0.45f;
            window.setAttributes(lp);
            window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            //设置背景透明
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        }
    }

    private void showShort(String msg) {
        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
    }

    public interface OnConnectBack {
        void back(BluetoothDevice bluetoothDevice);
    }
}
